#include "include/MyRedisD.h"

using namespace std;


MyRedisD::MyRedisD(std::string host, int port, int thread_pool_num) 
    : NIOServer(host, port, thread_pool_num){

}

// 对buf和offset进行相应的解包，然后进行相应的操作
// 参数：(buf, offset,sock_fd)
// return： 0正常，-1关闭sock继续，-2错误！
int MyRedisD::unpack_and_pack(char *&buf, int offset, int sock_fd)
{
    // 解包，一次性读完的 "get key val"
    string operate, key, val; 
    buf[offset] = '\0';
    printf("recv= %s \n", buf);
    string the_pack(buf, offset);
    vector<string> th = split_by(the_pack, " ");
    if( th.size() != 3 ){
        cout << "unpack error!"<< endl;
        sprintf(buf, "unpack error!");
        int ret = sendAllData(sock_fd, strlen(buf), buf); // head + body
        if (ret == -1)
        {
            printf("sendAllData==-1, close fd = %d \n", sock_fd);
            return -1;
        }
        return -1;
    }else{
        operate=th[0];
        key=th[1];
        val=th[2];
    }

    // 处理函数
    string res = "";
    cout << "正在处理:\n"  << endl;
    if( operate == "get" ){
        string* ret = skp.find(key); 
        if( ret ) res = *ret;
        else res = "NULL";
    }else if(operate == "set"){
        int ret = skp.insert(key, val);
        if (ret) res = "succ";
        else res="update";
    }else if(operate == "remove"){
        int ret = skp.remove(key);
        if (ret) res = "succ";
        else res="notfound";
    }
    
    printf(" 准备发送 \n");
    int AllLen= strlen(res.c_str());
    strcpy(buf, res.c_str() );
    
    
    int ret = sendAllData(sock_fd, AllLen, buf); // head + body
    if (ret == -1)
    {
        printf("sendAllData==-1, close fd = %d \n", sock_fd);
        return -1;
    }
     
    printf("该请求处理完毕:connfd=%d\n", sock_fd);
    // close(sock_fd); //如果是connnction=close
    return 0; // 正常
}

// 启动服务器
void testMyRedisD(){
    MyRedisD redisD("0.0.0.0", 6378, 1);
    redisD.startNIOServer();
}